package yx.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import yx.service.PublicArchiveServiceInt;
import yx.service.TreeServiceInt;
import yx.utils.DateUtils;
import yx.vo.ArchiveVO;
import yx.vo.DatagridVO;
import yx.vo.JsonVO;
import yx.vo.PublicArchiveVO;
import yx.vo.UserVO;

import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("basePackage")
@Namespace("/")
@Action(value = "publicArchiveAction")
public class PublicArchiveAction extends BaseAction implements ModelDriven<PublicArchiveVO> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PublicArchiveAction.class);
	
	private static final String rootPath = "/attachFiles/";

	private PublicArchiveVO publicArchive = new PublicArchiveVO();

	@Override
	public PublicArchiveVO getModel() {
		return publicArchive;
	}

	private PublicArchiveServiceInt publicArchiveService;
	
	public PublicArchiveServiceInt getPublicArchiveService() {
		return publicArchiveService;
	}

	@Autowired
	public void setPublicArchiveService(PublicArchiveServiceInt publicArchiveService) {
		this.publicArchiveService = publicArchiveService;
	}
	
	public void queryPublicArchive() {
		super.writeJson(publicArchiveService.datagrid(publicArchive));
	}
	
	public void queryPublicArchiveList() {
		JsonVO j = new JsonVO();
		DatagridVO vo = publicArchiveService.datagrid(publicArchive);
		if(vo.getTotal() == 0){
			j.setSuccess(true);
		} else {
			j.setSuccess(false);
			j.setMsg("当前节点已经存在文档，不允许为其创建下级目录！");
		}
		super.writeJson(j);
	}

	public void addPublicArchive() {
		FileOutputStream fos = null;
		FileInputStream fis = null;
		JsonVO j = new JsonVO();
		try {
			// 以服务器的文件保存地址和原文件名建立上传文件输出流
			String savePath = ServletActionContext.getServletContext().getRealPath(rootPath);
			File saveDir = new File(savePath);
			if (!saveDir.exists()) {
				saveDir.mkdir();
			}
			if (publicArchive.getArchive() != null && publicArchive.getArchive().length() > 0) {
				// TODO: 上传文件类型是否进行限制
				if (publicArchive.getArchive().length() <= 20971520) {
					HttpSession session = ServletActionContext.getRequest().getSession();
					UserVO user = (UserVO) session.getAttribute("LOGIN_USER");
					String ymdStr = DateUtils.getSystemDateTime("yyyyMMddHHmmss");

					int ind = publicArchive.getArchiveFileName().indexOf(".");
					String fileNamePart2 = publicArchive.getArchiveFileName().substring(ind);

					// 完整文档名
					String fullArchiveName = user.getId().toString() + "_" + ymdStr + fileNamePart2;
					publicArchive.setArchiveNo(fullArchiveName);

					fos = new FileOutputStream(savePath + File.separator + fullArchiveName);
					fis = new FileInputStream(publicArchive.getArchive());
					// 一次读取8K
					byte[] buffer = new byte[8192];
					int len = 0;
					while ((len = fis.read(buffer)) > 0) {
						fos.write(buffer, 0, len);
					}
					publicArchive.setUploaderId(user.getId());
					publicArchive.setUploaderName(user.getRealName());
					publicArchive.setRootPath(savePath);
					publicArchive.setContentType(publicArchive.getArchiveContentType());
					PublicArchiveVO u = publicArchiveService.save(publicArchive);
					j.setSuccess(true);
					j.setMsg("增加成功！");
					j.setObj(u);
				} else {
					j.setMsg("上传文件必须小于20M！");
				}
			} else {
				j.setMsg("上传文件为空！");
			}
		} catch (FileNotFoundException e) {
			String msg = "文件不存在！";
			j.setMsg(msg);
			logger.error(msg);
		} catch (IOException e) {
			String msg = "文件读写错误！";
			j.setMsg(msg);
			logger.error(msg);
		} catch (Exception e) {
			String msg = "上传文件出现错误";
			j.setMsg(msg);
			logger.error(msg);
		} finally {
			close(fos, fis);
			super.writeJson(j);
		}
	}

	public void removePublicArchive() {
		publicArchiveService.remove(publicArchive.getIds());
		JsonVO j = new JsonVO();
		j.setSuccess(true);
		j.setMsg("删除成功！");
		super.writeJson(j);
	}
	
	public void downloadPublicArchive() {
		OutputStream os = null;
		byte[] bytes = null;
		try {
			Integer id = publicArchive.getId();
			if (id != null && !"".equals(id)) {
				PublicArchiveVO vo = publicArchiveService.getPublicArchiveById(publicArchive);
				if (vo != null) {
					String fullFilePath = vo.getRootPath() + File.separator + vo.getArchiveNo();
					bytes = publicArchiveService.getFileBytes(fullFilePath);
					String archiveNo = vo.getArchiveNo();
					ServletActionContext.getResponse().reset();
					ServletActionContext.getResponse().setCharacterEncoding("utf-8");
					ServletActionContext.getResponse().setHeader("Content-Type", "application/octet-stream");
					ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment; filename=" + archiveNo);
					os = ServletActionContext.getResponse().getOutputStream();
					if (bytes != null) {
						os.write(bytes);
						os.flush();
						os.close();
					}
					logger.info("文档下载成功！");
				} else {
					logger.info("指定文档不存在！");
				}
			}
		} catch (Exception e) {
			logger.info("文档下载失败！");
		} finally {
			try {
				if (bytes != null) {
					os.write(bytes);
					os.flush();
				}
				os.close();
			} catch (IOException e) {
				logger.info("流文件关闭异常！");
			}
		}
	}
	
	private void close(FileOutputStream fos, FileInputStream fis) {
		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				logger.error("FileInputStream关闭失败");
			}
		}
		if (fos != null) {
			try {
				fos.close();
			} catch (IOException e) {
				logger.error("FileOutputStream关闭失败");
			}
		}
	}
}
